import time
import pyautogui
import win32com.client as win32

# 定义 DeepSeek API 请求函数
import requests

import time
import win32com.client as win32

# 启动 WPS
wps = win32.gencache.EnsureDispatch("KWPS.Application")
wps.Visible = True

# 增加等待时间，确保 WPS 完全启动
time.sleep(10)  # 可以根据实际情况调整等待时间

# 尝试访问 VBA 编辑器
try:
    vb_editor = wps.VBE
    print("成功访问 VBA 编辑器")
except Exception as e:
    print(f"访问 VBA 编辑器时出错: {e}")

def call_deepseek_api(prompt, api_key):
    url = "http://36.170.109.143:10555/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "model": "DeepSeek-R1-Distill-Llama-70B",
        "messages": [{"role": "user", "content": prompt}]
    }
    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 200:
        return response.json()["choices"][0]["message"]["content"]
    else:
        return f"Error: {response.text}"

# 模拟人工操作 WPS 并运行 VB 宏
def simulate_wps_operation(api_key):
    # 启动 WPS 文字
    try:
        wps = win32.gencache.EnsureDispatch("KWPS.Application")
        wps.Visible = True
    except Exception as e:
        print(f"启动 WPS 失败: {e}")
        return

    # 新建文档
    doc = wps.Documents.Add()
    time.sleep(2)

    # 模拟输入一段文本作为提示
    pyautogui.typewrite("请帮我总结这段内容的要点。")
    time.sleep(1)

    # 打开 VBA 编辑器
    wps.CommandBars.ExecuteMso("MacroSecurityDialog")
    time.sleep(2)
    # 假设启用所有宏（实际中可根据需求调整）
    pyautogui.press('down', presses=3)
    pyautogui.press('enter')
    time.sleep(2)

    wps.CommandBars.ExecuteMso("VisualBasicEditor")
    time.sleep(2)

    # 插入新模块
    vb_editor = wps.VBE
    module = vb_editor.VBProjects(1).VBComponents.Add(1)

    # 编写 VBA 宏代码
    vba_code = f"""
Sub CallDeepSeek()
    Dim apiKey As String
    Dim prompt As String
    Dim result As String
    apiKey = "{api_key}"
    prompt = ActiveDocument.Content.Text
    ' 这里调用 Python 脚本处理 DeepSeek 请求
    Shell "python -c ""import sys; from __main__ import call_deepseek_api; print(call_deepseek_api(sys.argv[1], sys.argv[2]))"" " & Chr(34) & prompt & Chr(34) & " " & apiKey, vbHide
    ' 这里简单模拟从文件读取结果，实际需要根据情况处理
    Open "temp_result.txt" For Input As #1
    result = Input$(LOF(1), 1)
    Close #1
    ActiveDocument.Content.InsertAfter result
End Sub
    """
    module.CodeModule.AddFromString(vba_code)

    # 关闭 VBA 编辑器
    vb_editor.MainWindow.Close()
    time.sleep(2)

    # 运行宏
    wps.Run("CallDeepSeek")
    time.sleep(5)

    # 保存文档
    doc.SaveAs2(r"C:\Temp\WPS_DeepSeek_Demo.docx")
    doc.Close()
    wps.Quit()

if __name__ == "__main__":
    # 替换为你的 DeepSeek API 密钥
    api_key = "YOUR_DEESEEK_API_KEY"
    simulate_wps_operation(api_key)